// 核心功能模块
const translationModule = {
    // 伪翻译接口
    async translate(text) {
        try {
            return await apiService.translateClassic(text);
        } catch (error) {
            console.error('翻译失败:', error);
            return {
                translation: '翻译服务暂时不可用',
                annotations: [],
                errors: ['网络错误']
            };
        }
    },

    // 章回体生成器
    generateChapter(text) {
        const plotPoints = text.match(/[^。！？]+[。！？]/g) || [];
        return plotPoints.map((p, i) =>
            `第${i+1}回 ${p.slice(0,15)}... ${i < plotPoints.length-1 ? '且听下回分解' : ''}`
        ).join('\n');
    },

    // 句法错误检测
    checkGrammar(text) {
        const errors = [];
        // 示例检测规则
        // if (!text.includes('之')) errors.push('缺少虚词"之"');
        if (text.length > 50) errors.push('句式过长需断句');
        return errors;
    }
};

// 界面交互逻辑
// 路由配置
const routes = {
    '#translate': 'translate-section',
    '#generate': 'generate-section',
    '#exercise': 'exercise-section'
};

// 改造后的切换函数
function switchTab(tabName) {
    window.location.hash = `#${tabName}`;
    handleRouting();
    if (tabName === 'exercise') {
        initExerciseInterface();
    }
}

translationModule.translateText = async function () {
    const btn = document.getElementById('translate-btn');
    btn.disabled = true;
    btn.classList.add('loading');
    btn.textContent = '翻译中...';
    try {
        const input = document.getElementById('classic-text').value.trim();

        if (!input) {
            document.getElementById('classic-text').classList.add('error-border');
            document.getElementById('translation-result').innerHTML = '<p class="error-message">请输入要翻译的文言文内容</p>';
            return;
        }

        const result = await translationModule.translate(input);

        document.getElementById('translation-result').innerHTML = `
            <p class="translation-text">${result.translation}</p>
            <div class="analysis-section">
                <h4>解析：</h4>
                <p>${result.analysis}</p>
            </div>
        `;
        document.getElementById('historical-context').innerHTML =
            result.annotations.map(a => `<p>📖 ${a}</p>`).join('');

        const errors = translationModule.checkGrammar(input);
        if (errors.length) {
            alert(`发现${errors.length}处句法错误：\n${errors.join('\n')}`);
        }
    } catch (error) {
        console.error('翻译失败:', error);
    } finally {
        btn.disabled = false;
        btn.classList.remove('loading');
        btn.textContent = '智能解析';
    }
}

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    // 默认显示翻译区块
    window.location.hash = '#translate';
    handleRouting();

    document.getElementById('classic-text').addEventListener('input', e => {
        if (e.target.value.length > 500) {
            alert('输入内容过长，建议分次翻译');
        }
    });

    // 绑定翻译按钮点击事件
    document.getElementById('translate-btn').addEventListener('click', translationModule.translateText);
});

// 添加路由监听
window.addEventListener('popstate', handleRouting);
document.querySelectorAll('.nav-item').forEach(item => {
    item.addEventListener('click', () => {
        switchTab(item.dataset.route);
    });
});

// 路由处理函数
function handleRouting(event) {
    const hash = window.location.hash || '#translate';
    const sectionId = routes[hash];

    document.querySelectorAll('.content > div').forEach(div => {
        div.style.display = 'none';
    });

    if (sectionId) {
        document.getElementById(sectionId).style.display = 'block';
    }

    // 更新导航按钮激活状态
    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.toggle('active', item.dataset.route === hash.slice(1));
    });
}



function initExerciseInterface() {
    const grade = document.querySelector('.grade-tabs .tab-btn.active').dataset.grade;
    const articles = exerciseData[grade];
    const articleList = document.querySelector('.article-list');

    articleList.innerHTML = articles.map(article =>
        `<button class="article-btn" data-grade="${grade}" data-title="${article.title}">
            ${article.title}
        </button>`
    ).join('');

    // 添加文章点击事件监听
    articleList.addEventListener('click', (e) => {
        if (e.target.closest('.article-btn')) {
            const btn = e.target.closest('.article-btn');
            loadArticle(btn.dataset.grade, btn.dataset.title);
        }
    });
}

// 添加年级切换事件监听
document.querySelectorAll('.grade-tabs .tab-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        document.querySelectorAll('.tab-btn').forEach(t => t.classList.remove('active'));
        btn.classList.add('active');
        initExerciseInterface();
    });
});

// 修正loadArticle函数
window.loadArticle = function (grade, title) {
    const article = exerciseData[grade].find(a => a.title === title);
    const exerciseArea = document.querySelector('.exercise-area');
    const processed = processContent(article.content);

    exerciseArea.classList.add('split-layout');
    document.querySelector('.content-display').innerHTML =
        `<div class="exercise-content">
            <div class="processed-content">${processed.html}</div>
       
            <button class="check-btn" onclick="checkAnswers()">提交答案</button>
        </div>`;

    window.checkAnswers = () => {
        const checkBtn = document.querySelector('.check-btn');
        checkBtn.disabled = true;

        let hasAnswered = false;
        const inputs = document.querySelectorAll('.blank input');
        let hasEmpty = false;

        if (hasAnswered) {
            alert('已提交过答案，请刷新页面重新练习！');
            return;
        }

        inputs.forEach(input => {
            if (!input.value.trim()) {
                input.classList.add('error-border');
                hasEmpty = true;
            }
        });

        if (hasEmpty) {
            alert('请填写所有空白处后再提交！');
            return;
        }

        inputs.forEach(input => {
            const correct = input.value.trim() === processed.answers[input.dataset.index];
            input.classList.toggle('correct', correct);
            input.classList.toggle('error', !correct);
        });

        if (!hasAnswered) {
            const answerContainer = document.createElement('div');
            answerContainer.className = 'answer-container';
            answerContainer.innerHTML = `
                <h4>正确答案：</h4>
                <ul class="answer-list">
                    ${processed.answers.map((a, i) => 
                        `<li>第${i+1}空：${a}</li>`
                    ).join('')}
                </ul>
            `;
            document.querySelector('.exercise-content').appendChild(answerContainer);
            hasAnswered = true;
        }
    }
}

function processContent(content) {
    const sentences = content.split(/(?<=[。？！])/g).filter(s => s.trim());
    const blanks = new Set();
    while (blanks.size < Math.floor(sentences.length * 0.3)) {
        blanks.add(Math.floor(Math.random() * sentences.length));
    }

    return {
        html: sentences.map((s, i) =>
            blanks.has(i) ? `<span class="blank"><input type="text" data-index="${i}"></span>` : s
        ).join(' '),
        answers: sentences.filter((_, i) => blanks.has(i))
    };
}

import {
    apiService
} from './api-service.js';
import {
    exerciseData
} from './exercise-data.js';